package com.ouyunc.oauth2.service.impl;


import com.ouyunc.oauth2.config.override.IRedisTokenStore;
import com.ouyunc.oauth2.service.IConsumerTokenServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Service;

/**
 * @Author fangzhenxun
 * @Description token 处理删除相关实现类，具体看ConsumerTokenServices接口
 * @Date 2020/7/8 18:05
 **/
@Service
public class IConsumerTokenServicesImpl implements IConsumerTokenServices {

    /**
     * 使用懒加载，注入bean,防止出现问题
     **/
    @Lazy
    @Autowired
    private IRedisTokenStore tokenStore;

    /**
     * @Author fangzhenxun
     * @Description 退出登陆，移除token
     * @Date 2020/7/8 18:50
     * @param tokenValue access_token
     * @return boolean
     **/
    @Override
    public boolean revokeToken(String tokenValue) {
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
        if (accessToken == null) {
            //可能存在access_token过期，refresh_token 没有过期的情况
            String refreshToken = tokenStore.readRefreshTokenByAccessToken(tokenValue);
            tokenStore.removeRefreshToken(refreshToken);
            return true;
        } else {
            if (accessToken.getRefreshToken() != null) {
                tokenStore.removeRefreshToken(accessToken.getRefreshToken());
            }
            //自己定义的删除redis
            tokenStore.completelyRemoveAccessToken(accessToken);
        }
        return true;
    }
}
